<template>
  <div v-loading="state.loading" :element-loading-background="state.elementLoadingBackground" style="width: 100%;"
       :title="($attrs.multiple === true || $attrs.multiple === '') ? state.paramVal?.map?.(v => optionsMapCpt?.get(v)?.__label) : optionsMapCpt?.get(state.paramVal)?.__label">
    <el-tree-select
        style="width: 100%;"
        v-bind="$attrs"
        v-model="state.paramVal"
        :placeholder="((typeof $attrs.disabled !== 'undefined' && $attrs.disabled !== false) || state.formView) ? '' : ($attrs.placeholder ? $attrs.placeholder : `请选择${label}`)"
        :data="options"
        :clearable="isValue($attrs.clearable) ? $attrs.clearable : true"
        :filterable="isValue($attrs.filterable) ? $attrs.filterable : true"
        :check-strictly="checkStrictly"
        :disabled="isValue($attrs.disabled) ? $attrs.disabled : state.formView"
        :nodeKey="nodeKey"
    >
      <template v-if="$slots.default" #default="prop">
        <slot name="default" v-bind="prop"/>
      </template>
    </el-tree-select>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  reactive,
  watch,
  inject
} from 'vue'
import {isValue} from "@/utils/czr-util";
const emit = defineEmits(['emitParam'])
const props = defineProps({
  param: {},
  label: {},
  checkStrictly: { default: true },
  options: { type: Array, default: () => [] },
  static: { default: false },
  isLoading: { default: false },
  props: {},
  nodeKey: {default: 'value'}
})
const state = reactive({
  paramVal: props.param,
  loading: true,
  elementLoadingBackground: inject('element-loading-background', null),
  formView: inject('form-view', false),
  defaultProps: {
    label: 'label',
  },
})
watch(() => state.paramVal, (n) => {
  emit('emitParam', n)
})
watch(() => props.param, (n) => {
  state.paramVal = n
})
watch(() => [props.options, props.static], () => {
  state.loading = false
})
const propsCpt = computed(() => {
  return props.props ? Object.assign(state.defaultProps, props.props) : state.defaultProps
})
const optionsMapCpt = computed(() => {
  const map = new Map()
  const deep = (arr) => {
    arr.forEach(v => {
      v.__value = v[props.nodeKey]
      v.__label = v[propsCpt.value.label]
      map.set(v.__value, v)
      if (v.children?.length > 0) {
        deep(v.children)
      }
    })
  }
  deep(props.options)
  return map
})
onMounted(() => {
  if (props.static !== false || props.options?.length > 0) {
    state.loading = false
  }
})
</script>

<style scoped lang="scss">
</style>
